package com.benyanyi.loglib;

import android.app.Application;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author myLove
 * @time 2017/10/31 10:41
 * @e-mail ben@yanyi.red
 * @overview
 */

class BaseLog {

    private static final int MAX_LENGTH = 4000;

    static void printDefault(LogType type, String tag, String msg) {
        int index = 0;
        int length = msg.length();
        int countOfSub = length / MAX_LENGTH;

        if (countOfSub > 0) {
            for (int i = 0; i < countOfSub; i++) {
                String sub = msg.substring(index, index + MAX_LENGTH);
                printSub(type, tag, sub);
                index += MAX_LENGTH;
            }
            printSub(type, tag, msg.substring(index, length));
        } else {
            printSub(type, tag, msg);
        }
    }

    private static void printSub(LogType type, String tag, String sub) {
        if (Jlog.mConfig.isShowLog() || Jlog.IS_INIT) {
            switch (type) {
                case V:
                    Log.v(tag, sub);
                    break;
                case D:
                    Log.d(tag, sub);
                    break;
                case I:
                    Log.i(tag, sub);
                    break;
                case W:
                    Log.w(tag, sub);
                    break;
                case E:
                    Log.e(tag, sub);
                    break;
                case A:
                    Log.wtf(tag, sub);
                    break;
            }
        }
        if (!Jlog.mConfig.isWrite()) {
            return;
        }
        if (!Jlog.mConfig.isShowWrite() && Jlog.mConfig.isShowLog()) {
            return;
        }
        writeLog(tag, sub);
    }

    /**
     * 记录报错日志
     */
    static void writeError(String tag, Throwable throwable) {
        StringWriter writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        throwable.printStackTrace(printWriter);
        Throwable cause = throwable.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String s = writer.toString();
        writeLog(tag, s);
    }

    /**
     * 记录日志
     */
    static void writeLog(String tag, String exceptionDescription) {
        try {
            String ROOT_PATH;
            if (TextUtils.isEmpty(Jlog.mConfig.getWriteRootPath()) || Jlog.mConfig.getWriteRootPath().equalsIgnoreCase("null")) {
                Application application = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
                assert application != null;
                String packageName = application.getPackageName();
                if (exceptionDescription == null || TextUtils.isEmpty(packageName)) {
                    return;
                }
                String fileName = packageName;
                String[] split = packageName.split("\\.");
                if (split != null) {
                    fileName = split[split.length - 1];
                }
                ROOT_PATH = Environment.getExternalStorageDirectory() + "/" + fileName + "/";
            } else {
                ROOT_PATH = Jlog.mConfig.getWriteRootPath();
            }
            File rootFile = new File(ROOT_PATH);
            try {
                if (!rootFile.exists()) {
                    rootFile.mkdir();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            File logPath = new File(ROOT_PATH + "/log/");
            try {
                if (!logPath.exists()) {
                    logPath.mkdir();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);// HH:mm:ss
            //获取当前时间
            Date date = new Date(System.currentTimeMillis());
            File logFile = new File(logPath + "/" + simpleDateFormat.format(date) + ".txt");
            try {
                if (logPath.exists() && !logFile.exists()) {
                    logFile.createNewFile();
                }
            } catch (Exception e) {
            }
            FileWriter fw = null;
            if (logFile.exists()) {
                try {
                    fw = new FileWriter(logFile, true);
                    if (TextUtils.isEmpty(tag)) {
                        fw.write(getTimeString() + "\t\t" + exceptionDescription + "\r\n");
                    } else {
                        fw.write(getTimeString() + "\t\t" + tag + "\t\t" + exceptionDescription + "\r\n");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fw != null) {
                        fw.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static long getFileSizes(File f) {
        long s = 0;
        if (f.exists()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(f);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                assert fis != null;
                s = fis.available();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("文件不存在");
        }
        return s;
    }

    /**
     * 获取时间
     *
     * @return str
     */
    static String getTimeString() {
        SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        return dateStr.format(new Date());
    }
}
